package com.example.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


@RestController
public class TestController {
    //从application.yml中获取值
    @Value("${top.ambt}")
    private String path;

    @GetMapping("/test")
    public String testGetValue(){
        System.out.println(path);
        return path;
    }


    String uploadPath = "E:";
    String fileName = "test.csv";
    /**
     * 测试文件上传，需要生成本地文件
     */
    @GetMapping("/download")
    public void fileDownload(HttpServletResponse response){
        InputStream in;
        BufferedInputStream bis;
        ServletOutputStream outputStream = null;
        try {
            //D:\\upload/a.jpg
            in=new FileInputStream(uploadPath+File.separator+fileName);
            bis=new BufferedInputStream(in);

            response.setHeader("content-type","application/force-download");
            response.setHeader("Content-Disposition","attachment;filename="+fileName);
            outputStream = response.getOutputStream();

            byte[] buffer=new byte[1024];
            int len=0;
            while((len=in.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }
            outputStream.flush();
            outputStream.close();
            in.close();
            System.out.println("下载成功");

        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试文件上传，需要生成本地文件
     */
//    @GetMapping("/download/{fileName}")
//    public void fileDownload(HttpServletResponse response,@PathVariable String fileName){
//        InputStream in;
//        BufferedInputStream bis;
//        ServletOutputStream outputStream = null;
//        try {
//            //D:\\upload/a.jpg
//            in=new FileInputStream(uploadPath+File.separator+fileName);
//            bis=new BufferedInputStream(in);
//
//            response.setHeader("content-type","application/force-download");
//            response.setHeader("Content-Disposition","attachment;filename="+fileName);
//            outputStream = response.getOutputStream();
//
//            byte[] buffer=new byte[1024];
//            int len=0;
//            while((len=in.read(buffer))!=-1){
//                outputStream.write(buffer,0,len);
//            }
//            outputStream.flush();
//            outputStream.close();
//            in.close();
//            System.out.println("下载成功");
//
//        } catch (FileNotFoundException e) {
//            System.out.println("文件未找到");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


}
